const { clientPublicPath } = require('./serverPluginClient');
const { readBody, injectScriptToHtml } = require('../../utils');
const LRUCache = require('lru-cache');

const devInjectionCode = `\n<script type="module">import "${clientPublicPath}"</script>\n`

const rewriteHtmlPluginCache = new LRUCache({ max: 20 })

function rewriteHtmlPlugin(context) {
  const { app } = context;

  app.use(async (ctx, next) => {

    await next()

    if (ctx.response.is('html') && ctx.body) {
      const html = await readBody(ctx.body)
      if (rewriteHtmlPluginCache.has(html)) {
        ctx.body = rewriteHtmlPluginCache.get(html)
      } else {
        if (!html) return
        const processedHtml = injectScriptToHtml(html, devInjectionCode);
        ctx.body = processedHtml;
        rewriteHtmlPluginCache.set(html, ctx.body)
      }
      return
    }
  })
}

module.exports = rewriteHtmlPlugin;